<?php
// 应用公共文件

use think\response\Json;

function eachArray(&$array)
{
    if ($array === []) {
        return new stdClass();
    }
    foreach ($array as &$value) {
        if (is_array($value) && !empty($value)) {
            $value = eachArray($value);
        }
        if ($value === []) {
            $value = new stdClass();
        }
    }
    return $array;
}

/**
 * @param  string  $msg  restfulAPI规范中的msg
 * @param  array  $data  restfulAPI规范中的data
 * @param  int  $code  restfulAPI规范中的code
 * @param  int  $http_code  http状态码
 * @param  array  $header  头部信息
 * @param  array  $options  json options
 * @return Json
 */
function retJson($msg = '', $data = [], $code = 0, $http_code = 200, $header = [], $options = [])
{
    return json(['code' => $code, 'msg' => lang($msg), 'data' => $data === [] ? $data : eachArray($data)], $http_code,
        $header, $options);
}

/**
 * @return string
 *
 * @Author: Li Guo Xin <guoxinlee129@gmail.com>
 * @Date: 2020/7/9
 * @Time: 11:54
 */
function createUuid()
{
    $arr    = openssl_random_pseudo_bytes(16);
    $arr[6] = chr(ord($arr[6]) & 0x0f | 0x40);
    $arr[8] = chr(ord($arr[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($arr), 4));
}

/**
 * 获取token
 * @return string
 *
 * @Author: Li Guo Xin <guoxinlee129@gmail.com>
 * @Date: 2020/8/12
 * @Time: 14:47
 */
function getToken()
{
    return getUniqueStr().getUniqueStr();
}

/**
 * 获取唯一的id，中间是有字符的
 * @return string
 */
function getUniqueStr()
{
    return md5(uniqid(md5(microtime(true)), true));
}

/**
 * 加密密码 $salt
 * @param $str
 * @return bool|string
 * @throws Exception
 */
function cryptPassword($str)
{
    $result['salt']     = getUniqueStr();
    $result['password'] = crypt($str, $result['salt']);
    return $result;
}

//比对密码
function decryptPassword($newStr, $oldStr, $salt)
{
    return crypt($newStr, $salt) == $oldStr ? true : false;
}

function getPidParent($result, $pid)
{
    $tree = array();                                //每次都声明一个新数组用来放子元素
    foreach ($result as $v) {
        if ($v['pid'] === $pid) {                      //匹配子记录
            $v['children'] = getPidParent($result, $v['id']); //递归获取子记录
            if ($v['children'] === []) {
                unset($v['children']);             //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
            }
            $temp = ['id' => $v['id'], 'label' => $v['name'], 'pid' => $v['pid']];
            if (isset($v['children'])) {
                $temp['children'] = $v['children'];
            }
            if ($v['common'] === '1') {
                $temp['disabled'] = true;
                $temp['label']    .= '(公共权限)';
            }
            $tree[] = $temp;
        }
    }
    return $tree;                                  //返回新数组
}